<!--
 * @Author: shiweizhen 787632169@qq.com
 * @Date: 2025-06-23 17:37:54
 * @LastEditors: shiweizhen 787632169@qq.com
 * @LastEditTime: 2025-07-04 10:51:43
 * @Description: 
 * Copyright (c) 2025-present HBIS Digital Technology Co.,Ltd. All rights reserved. 
-->
<template>
  <DtDialog v-model="visible" size="large" :title="formData.id ? '编辑' : '新增'" destroy-on-close @close="handleClose()"
    @confirm="handleSubmit()">
    <el-form ref="formRef" :model="formData" :rules="rules">
      <el-form-item label="名称" prop="projectName" label-width="80px">
        <el-input v-model="formData.projectName" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="描述" prop="description" label-width="80px">
        <el-input v-model="formData.description" placeholder="请输入描述" />
      </el-form-item>
      <el-form-item label="数据集" prop="datasetId" label-width="80px">
        <el-select v-model="formData.datasetId" placeholder="请选择数据集" @change="handleDatasetChange">
          <el-option v-for="item in datasetList" :key="item.id" :label="item.content" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-table :data="formData.calculateCondition" border>
        <el-table-column label="字段" prop="field">
          <template #default="scope">
            <el-form-item :prop="`calculateCondition.${scope.$index}.field`" :rules="rules.field">
              <el-select v-model="scope.row.field" placeholder="请选择字段">
                <el-option v-for="item in fieldList" :key="item.originName" :label="item.name"
                  :value="item.originName" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="条件" prop="condition">
          <template #default="scope">
            <el-form-item :prop="`calculateCondition.${scope.$index}.condition`" :rules="rules.condition">
              <el-select v-model="scope.row.condition" placeholder="请选择条件">
                <el-option label="等于" value="eq" />
                <el-option label="不等于" value="ne" />
                <el-option label="在......中" value="between" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="值" prop="value">
          <template #default="scope">
            <el-form-item :prop="`calculateCondition.${scope.$index}.value`" :rules="rules.value">
              <el-input v-model="scope.row.value" placeholder="请输入值" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="danger" text @click="formData.calculateCondition.splice(scope.$index, 1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button class="my-4" type="primary" icon="Plus"
        @click="formData.calculateCondition.push({ field: '', condition: '', value: '' })">新增条件</el-button>
      <el-form-item label="指标" prop="calculateMetrics" label-width="80px">
        <el-select v-model="formData.calculateMetrics" placeholder="请选择指标">
          <el-option v-for="item in metricsList" :key="item.originName" :label="item.name" :value="item.originName" />
        </el-select>
      </el-form-item>
      <el-form-item label="计算方式" prop="calculateMethod" label-width="80px">
        <el-radio-group v-model="formData.calculateMethod">
          <el-radio label="sum">求和</el-radio>
          <el-radio label="avg">平均值</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </DtDialog>

</template>

<script lang="ts" setup>
import { getCurrentInstance } from 'vue'
import { DtDialog, ID } from 'hbisdt-design';
import { FormInstance, FormRules } from 'element-plus';
import { ProjectType, DatasetType, DatasetDetailType } from '@/api/project/types'
import { getDatasetList, getDatasetDetail, saveMiddle, editMiddle } from '@/api/project'
const vm = getCurrentInstance()!
const { useDialog, $modal } = vm.appContext.config.globalProperties
const { visible, openDialog, closeDialog, submitLoading, cancelLoading } = useDialog()
const emits = defineEmits(['close'])
const formRef = ref<FormInstance>()
const formData = ref<ProjectType>({
  projectName: '',
  description: '',
  datasetId: '',
  calculateCondition: [{ field: '', condition: '', value: '' }],
  calculateMetrics: '',
  calculateMethod: ''
})
const datasetList = ref<DatasetType[]>([])
const fieldList = ref<DatasetDetailType[]>([])
const metricsList = ref<DatasetDetailType[]>([])
const rules = ref<FormRules>({
  projectName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  datasetId: [{ required: true, message: '请选择数据集', trigger: 'change' }],
  calculateCondition: [{ required: true, message: '请选择字段', trigger: 'change' }],
  condition: [{ required: true, message: '请选择条件', trigger: 'change' }],
  value: [{ required: true, message: '请输入值', trigger: 'blur' }],
  calculateMethod: [{ required: true, message: '请选择计算方式', trigger: 'change' }],
  calculateMetrics: [{ required: true, message: '请选择指标', trigger: 'change' }]
})

const getList = async () => {
  const res = await getDatasetList()
  datasetList.value = res.data
}
const getDetail = async (id: ID) => {
  const res = await getDatasetDetail(id)
  fieldList.value = res.data.filter(item => item.type !== 3)
  metricsList.value = res.data.filter(item => item.type === 3)
}

const handleDatasetChange = () => {
  getDetail(formData.value.datasetId)
}
const handleOpen = (data?: ProjectType) => {
  if (data) {
    formData.value = { ...data, datasetId: String(data.datasetId) }
    getDetail(formData.value.datasetId)
  } else {
    formData.value = {
      projectName: '',
      description: '',
      datasetId: '',
      calculateCondition: [{ field: '', condition: '', value: '' }],
      calculateMetrics: '',
      calculateMethod: ''
    }
    fieldList.value = []
    metricsList.value = []
  }
  openDialog()
  getList()
}
const handleClose = (): void => {
  closeDialog()
}
const handleSubmit = (): void => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading()
      if (formData.value.id) {
        await editMiddle(formData.value)
        $modal.msgSuccess('编辑成功')
      } else {
        await saveMiddle(formData.value)
        $modal.msgSuccess('新建成功')
      }
      emits('close')
      cancelLoading()
      handleClose()
    }
  })
}

defineExpose({
  handleOpen
})
</script>